from apps.common.base.views import *
from apps.interface.client.models import Client
from .service import *
import threading
from . import reports
from . import reports_qlw

class ValidateCodeViewSet(BaseViewSet):
    def get_queryset(self):
        params = getRequestParams(self.request)
    serializer_class = ValidateCodeSerializer

    '''发送验证码'''
    @action(methods=['post'], detail=False, url_path='sendSms',authentication_classes=[],permission_classes=[])
    def sendSmsAPI(self, request):
        params = getRequestParams(request)
        if not params.get("phone"):
            return Response(response_message("手机号不能为空"))
        if len(params.get("phone"))!=11:
            return Response(response_message("手机号格式错误"))
        params['phone'] = params.get("phone")
        params['code'] = random_num(6)
        # 创建一条验证码记录
        _validateCode = ValidateCode.objects.create(phone=params.get('phone'), code=params.get('code'))
        # 5分钟后状态改为失效
        t = threading.Timer(300, setValidateCodeStatus,(_validateCode,))
        t.start()
        _client = Client.objects.filter(is_delete=0, clientname=params.get('clientname')).first()
        if isEmptyStr(_client.lessee.validateCodeCHN):
            return Response(response_message('验证码渠道字段缺失'))
        params['validateCodeCHN'] = _client.lessee.validateCodeCHN
        sendSmsForAli(params)
        return Response(response_success('发送成功'))

def setValidateCodeStatus(validateCode):
    _validateCode = ValidateCode.objects.get(id=validateCode.id)
    print('更新验证码为失效状态', _validateCode.status)
    if _validateCode.status != 2:
        _validateCode.__dict__.update(**{'status':3})
        _validateCode.save()